﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SimpleBlog.Models;
using SimpleBlog.ViewModels;
using SimpleBlog.Helpers;
using SimpleBlog.Infrastructure.Repositories;
using System.Net;

namespace SimpleBlog.Controllers
{
    public class BlogController : Controller
    {
        IPostRepository _postRepository;

        public BlogController(IPostRepository postRepository)
        {
            _postRepository = postRepository;
        }

        public ActionResult Index(int page = 1, int count = 5)
        {
            if (page < 1 || count < 1)
                throw new HttpException((int) HttpStatusCode.BadRequest, "Page or Count parameter has to be greater than 1.");
            var posts = _postRepository.GetAll(page, count, x => x.Created, true).ToList();
            var maxPage = Math.Max((int)Math.Ceiling((double)_postRepository.CountAll() / count), 1);
            PostListViewModel model = new PostListViewModel()
            {
                MaxPage = maxPage,
                Page = page,
                Items = posts.Select(x => new PostViewModel() { PostItem = x, Summary = true })
            };
            return View(model);
        }
    }
}
